import socket

def start_server(host='localhost', port=65432):
    # 创建一个 TCP/IP socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: #ipv4   TCP协议
        # 绑定到主机和端口
        s.bind((host, port))
        # 监听连接
        s.listen()
        print(f"服务器在 {host}:{port} 等待连接...")
        conn, addr = s.accept()  # 等待客户端连接
        with conn:
            print(f"连接来自 {addr}")
            while True:
                data = conn.recv(1024)  # 接收数据
                if not data:
                    break
                print(f"接收到: {data.decode('utf-8')}")
                conn.sendall(data)  # 回送相同的数据给客户端
            # 分块接收大文件
            # filename='xxxxxxx'
            # with open(filename, 'wb') as file:
            #     while True:
            #         chunk = conn.recv(1024)
            #         if not chunk:
            #             break
            #         file.write(chunk)


if __name__ == "__main__":
    start_server()



